﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using ZLCMS.Business;
using ZLCMS.Business.DwzFrame;
using ZLCMS.Data.Model;
using NHibernate;
using Senparc.Weixin.MP.Entities;
using NHibernate.Criterion;
using System.Collections.Generic;
using ZLCMS.Business.Util;
using Senparc.Weixin.MP.Helpers;
using DotNet.Common.NHibernateUtil;

namespace ZLCMS.Web.SystemManage.Weixin
{
    public partial class EditQuestionGame : System.Web.UI.Page
    {
        protected FrameHelper _frameHelper;

        protected WxGamesConfig _gameDb;

        protected WxMaterial _materialDb;

        private string _uid;

        protected string _userAccount;

        protected void Page_Load(object sender, EventArgs e)
        {
            _userAccount = UserKit.GetUserAccountFailLogin();

            _frameHelper = new FrameHelper(this);

            //初始化全局变量值
            InitializeGlobalValue();
            //初始化控件值
            InitializeContent();

            if (IsPostBack)
            {
                Save();
            }
        }

        #region 保存操作 新建/更新 +private void Save()
        /// <summary>
        /// 保存操作 新建/更新
        /// </summary>
        private void Save()
        {
            using (ISession session = SessionFactoryHelper.CreateSession())
            {
                ITransaction tran = session.BeginTransaction();

                try
                {
                    if (string.IsNullOrEmpty(_uid))//新建
                    {
                        //素材对象
                        _materialDb = new WxMaterial();

                        _materialDb.Title = tb_name.Text;
                        _materialDb.MsgType = "QUESTION";
                        _materialDb.CreateDate = DateTime.Now;
                        _materialDb.UpdateDate = DateTime.Now;
                        _materialDb.Status = "1";
                        _materialDb.OwnerAccount = _userAccount;

                        session.Save(_materialDb);

                        _gameDb = new WxGamesConfig();

                        _gameDb.Title = tb_name.Text;
                        _gameDb.Description = tb_desc.Text;
                        _gameDb.Content = txtContent.Value;

                        _gameDb.BeginDate = DateTime.Parse(tb_sdate.Text);
                        _gameDb.EndDate = DateTime.Parse(tb_edate.Text);
                        _gameDb.CreateDate = DateTime.Now;

                        _gameDb.AwardName1 = tb_an_1.Text;
                        _gameDb.AwardRatio1 = float.Parse(tb_rn_1.Text);
                        _gameDb.AwardSum1 = int.Parse(tb_sn_1.Text);
                        _gameDb.AwardName2 = tb_an_2.Text;
                        _gameDb.AwardRatio2 = float.Parse(tb_rn_2.Text);
                        _gameDb.AwardSum2 = int.Parse(tb_sn_2.Text);
                        _gameDb.AwardName3 = tb_an_3.Text;
                        _gameDb.AwardRatio3 = float.Parse(tb_rn_3.Text);
                        _gameDb.AwardSum3 = int.Parse(tb_sn_3.Text);
                        _gameDb.NeedConfig = cbxNeedConfig.Checked ? 1 : 0;

                        _gameDb.RuleDay = int.Parse(tb_day.Text);
                        _gameDb.RuleTimes = int.Parse(tb_times.Text);
                        _gameDb.ShowAwardList = ddl_show.SelectedValue;

                        _gameDb.WinNotice = tb_win.Text;
                        _gameDb.LostNotice = tb_lost.Text;
                        _gameDb.EndNotice = tb_end.Text;

                        _gameDb.GameOpenUrl = fc_open.Value;
                        _gameDb.GameEndUrl = fc_end.Value;

                        _gameDb.OwnerAccount = _userAccount;
                        _gameDb.GameType = "QUESTION";
                        _gameDb.Status = "SETTING";
                        _gameDb.MaterialId = _materialDb.Id;

                        session.Save(_gameDb);
                    }
                    else//修改
                    {
                        _materialDb.Title = tb_name.Text;

                        _gameDb.Title = tb_name.Text;
                        _gameDb.Description = tb_desc.Text;
                        _gameDb.Content = txtContent.Value;

                        _gameDb.BeginDate = DateTime.Parse(tb_sdate.Text);
                        _gameDb.EndDate = DateTime.Parse(tb_edate.Text);

                        //活动开始后，不能修改奖品数量
                        if (_gameDb.Status == "SETTING")
                        {
                            _gameDb.AwardName1 = tb_an_1.Text;
                            _gameDb.AwardRatio1 = float.Parse(tb_rn_1.Text);
                            _gameDb.AwardSum1 = int.Parse(tb_sn_1.Text);
                            _gameDb.AwardName2 = tb_an_2.Text;
                            _gameDb.AwardRatio2 = float.Parse(tb_rn_2.Text);
                            _gameDb.AwardSum2 = int.Parse(tb_sn_2.Text);
                            _gameDb.AwardName3 = tb_an_3.Text;
                            _gameDb.AwardRatio3 = float.Parse(tb_rn_3.Text);
                            _gameDb.AwardSum3 = int.Parse(tb_sn_3.Text);
                        }

                        _gameDb.RuleDay = int.Parse(tb_day.Text);
                        _gameDb.RuleTimes = int.Parse(tb_times.Text);
                        _gameDb.ShowAwardList = ddl_show.SelectedValue;
                        _gameDb.NeedConfig = cbxNeedConfig.Checked ? 1 : 0;

                        _gameDb.WinNotice = tb_win.Text;
                        _gameDb.LostNotice = tb_lost.Text;
                        _gameDb.EndNotice = tb_end.Text;

                        _gameDb.GameOpenUrl = fc_open.Value;
                        _gameDb.GameEndUrl = fc_end.Value;

                        session.Update(_materialDb);
                        session.Update(_gameDb);
                    }

                    session.Flush();
                    tran.Commit();
                }
                catch (System.Exception ex)
                {
                    tran.Rollback();

                    _frameHelper.Alert(new ReturnCode() { statusCode = 300, message = "操作出错-" + ex.Message });
                    return;
                }
            }

            _frameHelper.Alert(new ReturnCode()
            {
                statusCode = 200,
                message = "操作成功!",
                callbackType = "forward",
                forwardUrl = "/SystemManage/Weixin/Interaction/QuestionGame/EditQuestionGame.aspx?tabid=editQuestionGame&uid=" + _gameDb.Id
            });
        } 
        #endregion


        protected void BindQuestionItem(int gid)
        {
            using (ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
            {
                rp_shopaddr.DataSource = session.CreateCriteria<WxGameQuestionsItem>().Add(Expression.Eq("ObjectId", gid)).AddOrder(Order.Asc("ShowOrder")).List<WxGameQuestionsItem>();
                rp_shopaddr.DataBind();
            }
        }


        /// <summary>
        /// 生成对应的奖品信息
        /// </summary>
        /// <param name="session"></param>
        /// <param name="gameDb"></param>
        protected void CreateAward(ISession session, WxGamesConfig gameDb)
        {

        }

        #region 初始化全局变量 + protected void InitializeGlobalValue()
        /// <summary>
        /// 初始化全局变量
        /// </summary>
        protected void InitializeGlobalValue()
        {
            if (!IsPostBack)
            {
                ParamKit.Bind("YesNo_10", ddl_show, null, null, null, "-1", "-1");

                ViewState["uid"] = Request["uid"];
            }
            _uid = (string)ViewState["uid"];

            if (!string.IsNullOrEmpty(_uid))
            {
                using (ISession session = SessionFactoryHelper.CreateSession())
                {
                    try
                    {
                        _gameDb = session.CreateCriteria<WxGamesConfig>().Add(Expression.Eq("Id", int.Parse(_uid))).Add(Expression.Eq("OwnerAccount", _userAccount)).UniqueResult<WxGamesConfig>();

                        if (_gameDb == null)
                        {
                            throw new Exception("找不到对应的游戏配置记录.");
                        }
                        else
                        {
                            _materialDb = session.CreateCriteria<WxMaterial>().Add(Expression.Eq("Id", _gameDb.MaterialId)).Add(Expression.Eq("OwnerAccount", _userAccount)).UniqueResult<WxMaterial>();
                            if (_materialDb == null)
                            {
                                throw new Exception("找不到对应的素材记录");
                            }
                        }
                    }
                    catch (System.Exception ex)
                    {
                        _frameHelper.Alert(new ReturnCode() { statusCode = 300, message = "操作出错-" + ex.Message });
                        return;
                    }
                }
            }
        } 
        #endregion

        #region 填充页面内容
        /// <summary>
        /// 填充页面内容
        /// </summary>
        protected void InitializeContent()
        {
            //页面控件值
            if (!IsPostBack)
            {
                if (!string.IsNullOrEmpty(_uid))
                {
                    tb_name.Text = _gameDb.Title;
                    tb_desc.Text = _gameDb.Description;
                    txtContent.Value = _gameDb.Content;

                    tb_sdate.Text = _gameDb.BeginDate.ToString("yyyy-MM-dd");
                    tb_edate.Text = _gameDb.EndDate.ToString("yyyy-MM-dd");

                    tb_an_1.Text = _gameDb.AwardName1;
                    tb_rn_1.Text = _gameDb.AwardRatio1.ToString();
                    tb_sn_1.Text = _gameDb.AwardSum1.ToString();
                    tb_an_2.Text = _gameDb.AwardName2;
                    tb_rn_2.Text = _gameDb.AwardRatio2.ToString();
                    tb_sn_2.Text = _gameDb.AwardSum2.ToString();
                    tb_an_3.Text = _gameDb.AwardName3;
                    tb_rn_3.Text = _gameDb.AwardRatio3.ToString();
                    tb_sn_3.Text = _gameDb.AwardSum3.ToString();
                    cbxNeedConfig.Checked = _gameDb.NeedConfig == 1 ? true : false;

                    if (_gameDb.Status != "SETTING")
                    {
                        tb_an_1.Enabled = false;
                        tb_rn_1.Enabled = false;
                        tb_sn_1.Enabled = false;
                        tb_an_2.Enabled = false;
                        tb_rn_2.Enabled = false;
                        tb_sn_2.Enabled = false;
                        tb_an_3.Enabled = false;
                        tb_rn_3.Enabled = false;
                        tb_sn_3.Enabled = false;
                    }

                    tb_day.Text = _gameDb.RuleDay.ToString();
                    tb_times.Text = _gameDb.RuleTimes.ToString();
                    ddl_show.SelectedValue = _gameDb.ShowAwardList;

                    tb_win.Text = _gameDb.WinNotice;
                    tb_lost.Text = _gameDb.LostNotice;
                    tb_end.Text = _gameDb.EndNotice;

                    fc_open.Value = _gameDb.GameOpenUrl;
                    fc_end.Value = _gameDb.GameEndUrl;

                    BindQuestionItem(_gameDb.Id);
                }
                else
                {
                    tb_name.Text = "问答游戏";
                    tb_desc.Text = "亲，请点击进入问答游戏活动页面，考考你的智慧哦!";
                    txtContent.Value = "亲，请点击进入问答游戏活动页面，考考你的智慧哦!";

                    tb_sdate.Text = DateTime.Now.ToString("yyyy-MM-dd");
                    tb_edate.Text = DateTime.Now.AddMonths(1).ToString("yyyy-MM-dd");
                    
                    tb_rn_1.Text = "5";
                    tb_sn_1.Text = "5";
                    tb_rn_2.Text = "10";
                    tb_sn_2.Text = "50";
                    tb_rn_3.Text = "50";
                    tb_sn_3.Text = "500";
                    tb_day.Text = "1";
                    tb_times.Text = "1";
                    ddl_show.SelectedValue = "0";

                    tb_win.Text = "恭喜您，全部答中了！您的智力超过爱因斯坦了！";
                    tb_lost.Text = "再接再厉哟！";
                    tb_end.Text = "亲，活动已经结束，请继续关注我们的后续活动哦。";

                    fc_open.Value = "[{\"FileId\":\"0\",\"FilePath\":\"/Interface/weixin/images/activity-lottery-start.jpg\",\"FileName\":\"问答游戏.jpg\"}]";
                    fc_end.Value = "[{\"FileId\":\"0\",\"FilePath\":\"/Interface/weixin/images/activity-lottery-end.jpg\",\"FileName\":\"问答游戏.jpg\"}]";
                }
            }
        } 
        #endregion
    }
}
